import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css' // progress bar style

Vue.use(VueRouter)

import Layout from '@/layout'
import EmptyLayout from '@/layout/empty'

const userConstentRoutes = [ // 静态路由，不需要动态权限判断
    {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home'),
        meta: {
            title: '首页'
        },
        children: [
            {
                path: '/demand',
                name: 'demand',
                component: () => import('@/views/home_example/demand'),
                meta: {
                    title: '需求中心'
                }
            },
            {
                path: '/help',
                name: 'help',
                component: () => import('@/views/home_example/help'),
                meta: {
                    title: '帮助文档'
                }
            },
            {
                path: '/about',
                name: 'about',
                component: () => import('@/views/home_example/about'),
                meta: {
                    title: '关于'
                }
            }
        ]
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login'),
        meta: {
            title: '登录'
        }
    },
    {
        path: '/forgot',
        name: 'Forgot',
        component: () => import('@/views/forgot'),
        meta: {
            title: '忘记密码'
        }
    },
    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        children: [
            {
                path: 'dashboard',
                name: 'dashboard',
                component: () => import('@/views/index'),
                meta: {
                    title: store.state.settings.dashboardTitle
                }
            },
            {
                path: 'personal',
                component: EmptyLayout,
                redirect: '/personal/setting',
                meta: {
                    title: '个人中心',
                    breadcrumb: false
                },
                children: [
                    {
                        path: 'setting',
                        name: 'personalSetting',
                        component: () => import('@/views/Administrators/personal/setting'),
                        meta: {
                            title: '个人设置'
                        }
                    },
                    {
                        path: 'edit/password',
                        name: 'personalEditPassword',
                        component: () => import('@/views/Administrators/personal/edit.password'),
                        meta: {
                            title: '修改密码'
                        }
                    }
                ]
            },
            {
                path: 'reload',
                name: 'reload',
                component: () => import('@/views/reload')
            }
        ]
    }
]

// 模块化，首先引入在modules目录下需要用的router
import ProjectRequirementsLibrary from './modules/Administrators/project.requirements.library'
import ProjectReserveLibrary from './modules/Administrators/project.reserve.library'
import ProjectInitiationLibrary from './modules/Administrators/project.initiation.library'
import ProjectArchiveLibrary from './modules/Administrators/project.archive.library'
import ExpertInformationLibrary from './modules/Administrators/expert.information.library'
import ExpertTeamLibrary from './modules/Administrators/expert.team.library'
import ExpertTask from './modules/Administrators/expert.task'
import Announcement from './modules/Administrators/announcement'
import Notice from './modules/Administrators/notice'
import ApprovalInformation from './modules/Administrators/approval.information'
import ApprovePass from './modules/Administrators/approve.pass'
import ProjectApprovalInformation from './modules/Administrators/project.approval.info'
import ProjectApprovalPass from './modules/Administrators/project.approval.pass'
import UserManagement from './modules/Administrators/user.management'
import SafetyEvaluationOrganization from './modules/Administrators/safety.evaluation.organization'
import SafetyProductionInspectionOrganization from './modules/Administrators/safety.production.inspection.organization'
import OutsideSafetyEvaluationOrganization from './modules/Administrators/outside.safety.evaluation.organization'
import OrganizationIllegalInformation from './modules/Administrators/organization.illegal.information'
import SafetyAssessmentReportInformation from './modules/Administrators/safety.assessment.report.information'
import TaskManagement from './modules/GeneralUser/task.management'
import ScheduleManagement from './modules/GeneralUser/schedule.management'
import AnnualReport from './modules/GeneralUser/annual.report'
import MyProject  from './modules/GeneralUser/my.project'
import AllProject from './modules/GeneralUser/all.project'
import ProjectReport from './modules/GeneralUser/project.report'
import StatisticalReport from './modules/GeneralUser/statistical.report'
import OngoingProject from './modules/GeneralUser/ongoing.project'
import MyApply from './modules/GeneralUser/my.apply'
import Pending from './modules/GeneralUser/pending'
import AllApproval from './modules/GeneralUser/all.approval'
import Proclamation from './modules/GeneralUser/proclamation'
import Cicular from './modules/GeneralUser/cicular'
import ThisWeekRequirements from './modules/GeneralUser/this.week.requirements'
import ThisYearRequirements from './modules/GeneralUser/this.year.requirements'
import BeforeRequirements from './modules/GeneralUser/before.requirements'
import NewTeam from './modules/GeneralUser/new.team'
import MyTeam from './modules/GeneralUser/my.team'
import JoinedTeam from './modules/GeneralUser/joined.team'
import BasicInfoSettings from './modules/Administrators/basic.info.settings'
import DatabaseBackup from './modules/Administrators/database.backup'

let routeData
// 当 children 不为空的主导航只有一项时，则隐藏
let asyncRoutes = [ // 动态路由，需要动态权限判断 超级管理员登录路由
    {
        meta: {
            title: '项目库',
            icon: 'project-library'
        },
        children: [
            ProjectRequirementsLibrary,
            ProjectReserveLibrary,
            ProjectInitiationLibrary,
            ProjectArchiveLibrary
        ]
    },
    {
        meta: {
            title: '专家库',
            icon: 'expert-database'
        },
        children: [
            ExpertInformationLibrary,
            ExpertTeamLibrary,
            ExpertTask
        ]
    },
    {
        meta: {
            title: '机构库',
            icon: 'mechanism-database'
        },
        children: [
            SafetyEvaluationOrganization,
            SafetyProductionInspectionOrganization,
            OutsideSafetyEvaluationOrganization,
            OrganizationIllegalInformation,
            SafetyAssessmentReportInformation
        ]
    },
    {
        meta: {
            title: '消息管理',
            icon: 'message-center'
        },
        children: [
            Announcement,
            Notice
        ]
    },
    {
        meta: {
            title: '审批管理',
            icon: 'approval'
        },
        children: [
            ApprovalInformation,
            ApprovePass,
            ProjectApprovalInformation,
            ProjectApprovalPass
        ]
    },
    {
        meta: {
            title: '系统管理',
            icon: 'system'
        },
        children: [
            UserManagement,
            BasicInfoSettings,
            DatabaseBackup
        ]
    }
]

let userRoutes = [ // 动态路由，需要动态权限判断，用户登录路由
    {
        meta: {
            title: '工作台',
            icon: 'workbench'
        },
        children: [
            TaskManagement,
            ScheduleManagement,
            AnnualReport,
            MyProject
        ]
    },
    {
        meta: {
            title: '项目',
            icon: 'project-center'
        },
        children: [
            AllProject,
            ProjectReport,
            StatisticalReport,
            OngoingProject
        ]
    },
    {
        meta: {
            title: '审批',
            icon: 'approval-center'
        },
        children: [
            MyApply,
            Pending,
            AllApproval
        ]
    },
    {
        meta: {
            title: '消息',
            icon: 'message-center'
        },
        children: [
            Proclamation,
            Cicular
        ]
    },
    {
        meta: {
            title: '需求',
            icon: 'demand-center'
        },
        children: [
            ThisWeekRequirements,
            ThisYearRequirements,
            BeforeRequirements
        ]
    },
    {
        meta: {
            title: '团队',
            icon: 'team-center'
        },
        children: [
            NewTeam,
            MyTeam,
            JoinedTeam
        ]
    }
]

const lastRoute = [{
    path: '*',
    component: () => import('@/views/404'),
    meta: {
        title: '404',
        sidebar: false
    }
}]

const router = new VueRouter({
    // routes: constantRoutes
    routes: userConstentRoutes
})

// 解决路由在 push/replace 了相同地址报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
}

router.beforeEach(async(to, from, next) => {

    store.state.settings.enableProgress && NProgress.start()
    // 已经登录，但还没根据权限动态挂载路由
    if (store.getters['user/isLogin'] && !store.state.menu.isGenerate) {
        /**
         * 重置 matcher
         * https://blog.csdn.net/baidu_28647571/article/details/101711682
         */
        router.matcher = new VueRouter({
            // routes: constantRoutes
            routes: userConstentRoutes
        }).matcher
        // 根据用户权限设置动态路由
        routeData = store.getters['user/isAdmin'] ? asyncRoutes : userRoutes
        const accessRoutes = await store.dispatch('menu/generateRoutes', {
            routeData,
            currentPath: to.path
        })
        // accessRoutes.push(...lastRoute)
        // accessRoutes.forEach(route => {
        //     router.addRoute(route)
        // })
        accessRoutes.push(...lastRoute)
        accessRoutes.forEach(route => {
            router.addRoute(route)
        })
        next({ ...to, replace: true })
    }
    if (store.state.menu.isGenerate) {
        store.commit('menu/setHeaderActived', to.path)
    }
    to.meta.title && store.commit('settings/setTitle', to.meta.title)
    if (store.getters['user/isLogin']) {
        if (to.name) {
            if (to.matched.length !== 0) {
                // 如果已登录状态下，进入登录页会强制跳转到控制台页面 !!!!!!!!!!!
                if (to.name === 'login') {
                    next({
                        name: 'dashboard',
                        replace: true
                    })
                } else if (!store.state.settings.enableDashboard && to.name === 'dashboard') {
                    // 如果未开启控制台页面，则默认进入侧边栏导航第一个模块，但如果侧边栏导航没有模块，则还是进入控制台页面
                    if (store.getters['menu/sidebarRoutes'].length > 0) {
                        next({
                            name: store.getters['menu/sidebarRoutes'][0].name,
                            replace: true
                        })
                    }
                }
            } else {
                // 如果是通过 name 跳转，并且 name 对应的路由没有权限时，需要做这步处理，手动指向到 404 页面
                next({
                    path: '/404'
                })
            }
        }
    } else {
        // 这里是没登录状态时 任何路由都跳转到登录页  冉秀修改一下
        if (to.name !== 'login' && to.name !== 'Forgot' && to.name !== 'home') {
            next({
                name: 'home',
                query: {
                    redirect: to.fullPath
                }
            })
        }
    }
    // 百度统计代码
    if (process.env.VUE_APP_TYPE === 'example') {
        if (window._hmt) {
            window._hmt.push(['_trackPageview', location.pathname + '#' + to.fullPath])
        }
    }
    next()
})

router.afterEach(() => {
    store.state.settings.enableProgress && NProgress.done()
})

export default router
